<?php
 class ShopCartAction extends LockAction{
 	public function index(){
 		$id=$_GET['id'];
 		// pre($_SESSION);exit;
 		// 商品信息
 		$shop=M('Shop');
 		$shoprow=$shop->where('id='.$id)->find();
 		$_SESSION['shops'][$id]=$shoprow;
 		$_SESSION['shops'][$id]['num']=1;
 		unset($_SESSION['shops']['']);//清除session里的多余数据
 		$this->assign('shoprows',$_SESSION['shops']);

 		// 联系方式
 		$touch=M('Touch');
 		$touchrows=$touch->where('user_id='.$_SESSION['home_user_id'])->select();
 		$this->assign('touchrows',$touchrows);

 		$this->display();
 	}

 	// 增加商品数量
 	public function add(){
 		$id=$_GET['id'];
 		if($_SESSION['shops'][$id]['num']<$_SESSION['shops'][$id]['stock']){
 			$_SESSION['shops'][$id]['num']++;
 		}else{
 			$_SESSION['shops'][$id]['num']=$_SESSION['shops'][$id]['stock'];
 		};
 		$this->redirect('index');
 	}

 	// 减少商品数量
 	public function cut(){
 		$id=$_GET['id'];
 		if($_SESSION['shops'][$id]['num']>1){
 			$_SESSION['shops'][$id]['num']--;
 		}else{
 			$_SESSION['shops'][$id]['num']=1;
 		};
 		$this->redirect("index");
 	}

 	// 删除商品
 	public function delete(){
 		$id=$_GET['id'];
 		unset($_SESSION['shops'][$id]);
 		$this->redirect("index");
 	}

 	// 清空购物车
 	public function delAll(){
 		unset($_SESSION['shops']);
 		$this->redirect('index');
 	}

 	// 结算
 	public function payAll(){
 		$indent=M('Indent');
 		$data['code']=time().rand();
 		$data['user_id']=$_SESSION['home_user_id'];
 		$data['time']=time();
 		$data['touch_id']=$_POST['touch'];
 		foreach ($_SESSION['shops'] as $k => $v) {
 			$data['shop_id']=$v['id'];
 			$data['number']=$v['num'];
 			$data['status_id']=8;
 			$indent->add($data);
 			// 减库存
 			$nowstock=$v['stock']-$v['num'];//库存减去购买数量
 			$shoprow['id']=$v['id'];
 			$shoprow['stock']=$nowstock;
 			if($nowstock<1){
 				$shoprow['shelf']=0;//库存小于1下架
 			}
 			M('Shop')->save($shoprow);
 		}
 		// 清购物车
 		$_SESSION['shops']=array();
 		$this->success("您的订单号为：{$data['code']}",U('Index/index'));
 	}
 }
?>